package LeetCode.exercise;

import java.util.LinkedList;
import java.util.Queue;

public class LC130 {
    private int[] dx = {0, 0, 1, -1};
    private int[] dy = {1, -1, 0, 0};
    int m, n;
    boolean[][] flag = new boolean[m][n];
    public void solve(char[][] board) {
        m = board.length;
        n = board[0].length;
        for(int i = 0; i < n; i++) {
            if(board[0][i] == 'X') {
                bfs(board, 0, i);
            }
            if(board[m-1][i] == 'X') {
                bfs(board, m - 1, i);
            }
        }
        for(int i = 1; i < m-1; i++){
            if(board[i][0] == 'X') {
                bfs(board, i, 0);
            }
            if(board[i][n-1] == 'X') {
                bfs(board, i, n - 1);
            }
        }
        for(int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
                if (board[i][j] == '1') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    private void bfs(char[][] board, int i, int j) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{i, j});
        flag[i][j] = true;
        while (!queue.isEmpty()){
            int[] tmp = queue.poll();
            int a = tmp[0], b = tmp[1];
            for (int k = 0; k < 4; k++) {
                int x = a + dx[k], y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'o' && !flag[x][y]){
                    board[x][y] = '1';
                    queue.offer(new int[]{x, y});
                    flag[x][y] = true;
                }
            }
        }
    }
}
